package accountManagementNew.controller;

import accountManagementNew.common.base.Result;
import accountManagementNew.common.dto.UserDTO;
import accountManagementNew.common.enums.ResultCodeEnum;
import accountManagementNew.common.pojo.User;
import accountManagementNew.service.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * @Author：lihonbin
 * @version：2025/9/2
 * @description 用户控制器
 */
@RestController
@RequestMapping("/user")
@AllArgsConstructor
@Tag(name = "用户接口")
public class UserController {

    private final IUserService userService;

    /**
     * 判断用户名是否已存在
     *
     * @param username 用户名
     * @return 返回结果
     */
    @GetMapping("/isHave")
    @Operation(summary = "判断用户名是否已存在")
    public Result<String> queryUserNameIsHave(@Parameter(description = "用户名", required = true) @RequestParam String username) {
        Boolean isHave = userService.queryUserNameIsHave(username);
        if (isHave) {
            return Result.error(ResultCodeEnum.FAIL, "用户名已存在");
        }
        return Result.success();
    }

    /**
     * 注册用户
     *
     * @param user 用户信息
     * @return 注册结果
     */
    @PostMapping("/register")
    @Operation(summary = "注册用户")
    public Result<String> register(@Parameter(description = "用户信息", required = true) @RequestBody UserDTO user) {
        Boolean result = userService.registeredUser(user);
        if (!result) {
            return Result.error(ResultCodeEnum.FAIL, "注册失败");
        }
        return Result.success("注册成功", null);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 修改的用户信息
     * @return 修改结果
     */
    @PutMapping("/change")
    @Operation(summary = "修改用户基本信息")
    public Result<String> changeUserInfo(@Parameter(description = "修改用户基本信息", required = true) @RequestBody User user) {
        // 校验信息
        if (user == null || user.getId() == null) {
            return Result.error(ResultCodeEnum.FAIL, "修改失败");
        }
        boolean isUpdate = userService.updateById(user);
        if (!isUpdate) {
            return Result.error(ResultCodeEnum.FAIL, "修改失败");
        }
        return Result.success();
    }

    /**
     * 修改用户密码
     *
     * @param user 修改的用户信息
     * @return 修改结果
     */
    @PutMapping("/changePwd")
    @Operation(summary = "修改用户密码")
    public Result<String> changeUserPassword(@Parameter(description = "修改用户密码", required = true) @RequestBody User user) {
        // 校验信息
        if (user == null) {
            return Result.error(ResultCodeEnum.FAIL, "修改失败");
        }
        boolean isUpdate = userService.changeUserPassword(user);
        if (!isUpdate) {
            return Result.error(ResultCodeEnum.FAIL, "修改失败");
        }
        return Result.success();
    }

}